package com.zhiqingchun.dao.category.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import com.zhiqingchun.common.Page;
import com.zhiqingchun.dao.BaseDao;
import com.zhiqingchun.dao.category.CategoryResult;
import com.zhiqingchun.dao.category.ICategoryDao;
import com.zhiqingchun.pojo.CategoryDO;

public class CategoryDao extends BaseDao implements ICategoryDao {

	@Override
	public CategoryResult byId(int id) {
		String sql = "select * from category where id = ?";
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			CategoryResult categoryResult = new CategoryResult();
			CategoryDO categoryDO = new CategoryDO();
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				categoryDO.setId(id);
				categoryDO.setName(rs.getString("name"));
				categoryResult.setSuccess(true);
				categoryResult.setCategory(categoryDO);
			} 
			rs.close();
			ps.close();
			return categoryResult;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					
				}
			}
		}
	}
	
	private DataSource dataSource;

	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	@Override
	public CategoryResult list(CategoryDO categoryDO, Page page) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT * from category c where 1 = 1");
		List<Object> param = new ArrayList<Object>();
		if (categoryDO != null && categoryDO.getId() != null) {
			sql.append(" and c.parent = ?");
			param.add(categoryDO.getId());
		}
		sql.append(" order by c.no");
		List<Map<String, Object>> returnList = getJdbcBaseDao().findPageList(sql.toString(), param.toArray(), page);
		List<CategoryDO> list = new ArrayList<CategoryDO>();
		for (Map<String, Object> map : returnList) {
			CategoryDO c = new CategoryDO();
			c.setId((Integer) map.get("id"));
			c.setName(map.get("name").toString());
			list.add(c);
		}
		CategoryResult categoryResult = new CategoryResult();
		categoryResult.setSuccess(true);
		categoryResult.setCategoryList(list);
		return categoryResult;
	}

}
